<!-- 行政复议监督处理反馈材料 -->
<template>
  <div class="feedBack_div">
    <div style="margin-right: 20px;">
      <a-spin :spinning="loading">
        <div class="operate_btn_div">
          <a-button
            :loading="btnLoading"
            type="primary"
            v-if="category == 'rectify' && !isFinish && isEditModel"
            @click="completeMaterial()"
            style="float:right; margin:0px 10px;z-index:999;"
            class="btn_primary_color add_btn"> 整改完成 </a-button>
          <a-button
            :loading="btnLoading"
            v-if="category == 'rectify' && isEditModel"
            :disabled="!isFinish"
            @click="completeEnd()"
            style="float:right; margin:0px 10px;z-index:999;"
            class="btn_primary_color add_btn"> 提交 </a-button>
          <a-button
            type="primary"
            icon="plus"
            @click="handleAdd()"
            style="float:right; margin:0px 10px;z-index:999;"
            class="btn_normal_color add_btn"> 新增材料 </a-button>
        </div>
        <div v-if="materialList && materialList.length > 0">
          <a-table
            :columns="columns"
            :data-source="materialList"
            rowKey="id"
            :pagination="false"
            :loading="loading"
            bordered>
            <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
            <span slot="name" slot-scope="text, record" class="overBox">
              <a-input
                ref="refName"
                v-if="record.editable"
                v-model="record.name"
                placeholder="请输入材料名称"
              />
              <div v-else >{{ text }}</div>
            </span>
            <span slot="explain" slot-scope="text, record" class="overBox">
              <a-input
                v-if="record.editable"
                v-model="record.explain"
                placeholder="请输入材料说明"
              />
              <div v-else class="line">{{ record.explain }}</div>
            </span>
            <span slot="attachmentList" slot-scope="list, record, rIndex">
              <div v-if="list && list.length">
                <a v-for="item in list" :key="item.id" class="file-css">
                  <div style="width: 60%;display: flex;align-items: center;">
                    <span @click="fileView(item)" :title="item.filename" class="beyond_hiding">
                      <a-icon type="folder" theme="filled" />
                      {{ item.filename }}
                    </span>
                  </div>
                  <div style="width: 40%;display: flex;align-items: center;">
                    <div class="button_flex cursor_pointer" @click="downloadFile(item)">
                      <a-icon type="download" style="margin-right: 8px"/>
                      <a class="download_div" style="font-size: 14px;">下载</a>
                    </div>
                    <a-divider type="vertical" />
                    <a-popconfirm title="确定删除吗？" @confirm="() => removeFile(item, record)">
                      <div class="button_flex cursor_pointer">
                        <a-icon type="delete" style="margin-right: 8px;"/>
                        <a class="download_div">删除</a>
                      </div>
                    </a-popconfirm>
                  </div>
                </a>
              </div>
              <div v-else>
                未上传附件
              </div>
            </span>
            <span slot="operation" slot-scope="text, record">
              <template>
                <div v-if="!record.editable" style="display: flex;align-items: center;justify-content: center;">
                  <div @click="handleUpload(record, index)" class="cursor_pointer" style="margin-right: 10px;">
                    <a-icon type="upload" style="margin-right: 8px;color: #1890ff;"/>
                    <a>上传</a>
                  </div>
                  <a-divider type="vertical" />
                  <div @click="handleEdit(record, index)" class="cursor_pointer" style="margin-right: 10px;">
                    <a-icon type="edit" style="margin-right: 8px;color: #1890ff;"/>
                    <a>编辑</a>
                  </div>
                  <a-divider type="vertical" />
                  <a-popconfirm title="确定删除吗？" @confirm="() => handleRemove(record, index)">
                    <div class="button_flex">
                      <a-icon type="delete" style="margin-right: 8px;color: #1890ff;"/>
                      <a class="download_div">删除</a>
                    </div>
                  </a-popconfirm>
                </div>
                <div v-else style="display: flex;align-items: center;justify-content: center;">
                  <div class="button_flex">
                    <a-icon type="save" style="margin-right: 8px;color: #1890ff;" />
                    <a @click="handleSave(record, index)" class="cursor_pointer">保存</a>
                  </div>
                  <a-divider type="vertical" />
                  <a-popconfirm
                    title="确定取消修改吗？"
                    @confirm="() => handleCancle(record, index)"
                  >
                    <div class="button_flex">
                      <a-icon type="delete" style="margin-right: 8px;color: #1890ff;"/>
                      <a class="cursor_pointer">取消</a>
                    </div>
                  </a-popconfirm>
                </div>
              </template>
            </span>
          </a-table>
        </div>
        <a-empty v-else description="暂无材料数据" style="min-height: 400px" />
        <MultiUploadBasic ref="multiUploadBasic" @importFileFun="importFileFun"></MultiUploadBasic>
      </a-spin>
    </div>
  </div>
</template>

<script>
import { nanoid } from 'nanoid'
import { downloadFile, kkfilePreview } from '@/utils/util'
import { minioUpload, minioRemove, minioUploadMore } from '@/api/base/file'
import { queryFeedBackDocListByApplyid, saveFeedBackDoc, deleteFeedBackDoc } from '@/api/supervise/apl_feedbackdoc'
import storage from 'store'
import { APP_USER } from '@/store/mutation-types.js'
import { completeMaterial, completeEnd } from '@/api/supervise/businesssupervise.js'
import { viewSupervise } from '@/api/supervise/apl_supervise.js'
export default {
  props: {
    applyid: {
      // 申请id
      type: String,
      required: true
    },
    category: {
      type: String,
      required: false
    },
    taskid: {
      type: String,
      required: true
    },
    processinstanceid: {
      type: String,
      default: '',
      required: true
    },
    isEditModel: {
      type: Boolean,
      required: false
    }
  },
  data () {
    return {
      columns: [
        {
          title: '序号',
          dataIndex: 'serial',
          key: 'serial',
          align: 'center',
          width: '70px',
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '材料名称',
          dataIndex: 'name',
          key: 'name',
          align: 'center',
          width: '20%',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '材料说明',
          dataIndex: 'explain',
          align: 'center',
          width: '20%',
          key: 'explain',
          scopedSlots: { customRender: 'explain' }
        },
        {
          title: '附件信息',
          dataIndex: 'attachmentList',
          align: 'center',
          key: 'attachmentList',
          scopedSlots: { customRender: 'attachmentList' }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '240px',
          fixed: 'right',
          align: 'center',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      materialList: [],
      materialListBak: [],
      loading: false,
      selectRecord: {},
      collapseKey: [1], // 折叠面板key
      currentUser: storage.get(APP_USER), // 登录人信息
      btnLoading: false,
      superviseObj: null,
      isFinish: false
    }
  },
  components: {
    MultiUploadBasic: () => import('@/views/materials/multiUpload/MultiUploadBasic.vue')
  },
  async created () {
    await this.initData()
    this.queryList()
  },
  methods: {

    initData () {
      return new Promise(async (resolve) => {
        const res = await viewSupervise(this.applyid)
        if (res.code === 0) {
          this.superviseObj = res.data ? res.data : {}
          if (this.superviseObj.isfinish == 3200) {
            this.isFinish = true
          }
        } else {
          this.$message.error('查询复议监督数据异常')
        }
        return resolve(false)
      })
    },
    // 下载文件
    downloadFile (file) {
      var x = new XMLHttpRequest()
      x.open('GET', file.path, true)
      x.responseType = 'blob'
      x.onload = function (e) {
          var url = window.URL.createObjectURL(x.response)
          var a = document.createElement('a')
          a.href = url
          a.download = file.filename
          a.click()
      }
      x.send()
    },
    // 删除文件
    removeFile (file, record) {
      // 弹出确认框是否删除该文件
      this.$confirm({
        title: '提示',
        content: '确定删除该文件吗？',
        onOk: () => {
          const fileId = file.id
          this.loading = true
          const attachids = record.attachids
          let materials = attachids ? attachids.split(',') : []
          materials = materials.filter(el => el !== fileId)
          record.attachids = materials.join(',')
          saveFeedBackDoc(record).then(res => {
            if (res.code == 0) {
              console.log('删除文件成功', fileId)
              // 修改对应字段的文件的值
              minioRemove({ 'fileid': fileId }).then((res1) => {
                console.log('res', res1)
                if (res1.code !== 0) {
                  this.$message.error('删除文件失败')
                } else {
                  console.log('删除文件成功', fileId)
                  this.$message.success('删除文件成功')
                  // 对应类型去除该字段
                  // 重新查询数据
                  this.queryList()
                }
              }).finally(() => {
                this.loading = false
              })
            } else {
              console.log('删除文件失败', res)
            }
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    // 确保保存导入数据
    importFileFun (importFileList) {
      console.log('importFileList', importFileList)
      const files = []
      importFileList.forEach((item) => {
        files.push(item)
      })
      this.$refs.multiUploadBasic.loading = true
      minioUploadMore(files).then((res) => {
        if (res.code == 0) {
          const attachs = res.data
          // 更新字段
          const attachids = this.selectRecord.attachids
          const materials = attachids ? attachids.split(',') : []
          const newMaterials = attachs.map(el => el.id)
          const newArray = [...materials, ...newMaterials]
          const concatArray = Array.from(new Set(newArray))
          const newAttachids = concatArray.join(',')
          this.selectRecord.attachids = newAttachids

          saveFeedBackDoc(this.selectRecord).then(res => {
            if (res.code == 0) {
              this.$message.success('上传成功')
              this.$refs.multiUploadBasic.handleCancel()
              this.queryList()
            } else {
              this.$message.success('上传失败')
              this.$refs.multiUploadBasic.handleCancel()
            }
          })
        } else {
          this.$message.success('上传失败')
          this.$refs.multiUploadBasic.handleCancel()
        }
      }).finally(() => {
        this.$refs.multiUploadBasic.handleCancel()
      })
    },
    // 上传文件
    handleUpload (record, index) {
      this.selectRecord = record
      this.$refs.multiUploadBasic.importVisible = true
    },
    handleEdit (record, index) {
      record.editable = true
      for (let index = 0; index < this.materialList.length; index++) {
        if (this.materialList[index].id == record.id) {
          this.$set(this.materialList, index, record)
        }
      }
    },
    handleRemove (record, index) {
      deleteFeedBackDoc(record.id).then((res) => {
        if (res.code == 0) {
          // 重新刷新
          this.queryList()
          this.$message.success('删除成功')
        } else {
          this.$message.error('删除失败')
        }
      })
    },
    // 附件在线预览
    fileView (file) {
      console.log('文件预览', file)
      window.open(kkfilePreview(file.path))
    },
    // 查询数据
    queryList () {
      this.loading = true
      queryFeedBackDocListByApplyid(this.applyid).then((res) => {
        if (res.code == 0) {
          this.materialList = res.data
          if (this.materialList && this.materialList.length > 0) {
            this.materialList.forEach(el => {
              el.editable = false
            })
            this.materialListBak = JSON.parse(JSON.stringify(this.materialList))
          }
        } else {
          this.$message.error('查询失败')
        }
      }).finally(() => {
        this.loading = false
      })
    },
    handleAdd () {
      this.materialList.push({
        id: this.applyid + nanoid(),
        applyid: this.applyid,
        name: '',
        explain: '自定义材料',
        editable: true,
        attachids: undefined,
        createtime: new Date(),
        createuserid: this.currentUser.userId,
        createusername: this.currentUser.fullname
      })
    },

    async handleSave (record, index) {
      if (!record.name) {
        this.$message.error('请输入名称')
        return
      }
      const res = await saveFeedBackDoc(record)
      if (res.code == 0) {
        this.queryList()
      } else {
        this.$message.error('保存失败')
      }
    },
    handleCancle (record, index) {
      const materialBak = this.materialListBak.find(item => record.id === item.id)
      if (materialBak) {
        for (let index = 0; index < this.materialList.length; index++) {
          if (this.materialList[index].id === record.id) {
            this.materialList[index].name = materialBak.name
            this.materialList[index].explain = materialBak.explain
            this.materialList[index].editable = false
          }
          this.$set(this.materialList, index, this.materialList[index])
        }
      } else {
        this.materialList = this.materialList.filter(item => record.id !== item.id)
      }
    },
    // 整改完成
    completeMaterial () {
      this.btnLoading = true
      completeMaterial(this.applyid, this.taskid, this.currentUser.userId).then((res) => {
        if (res.code == 0) {
          this.$message.success('整改完成执行成功')
          this.initData()
        } else {
          this.$message.error('整改完成执行失败')
        }
      }).finally(() => {
        this.btnLoading = false
      })
    },
    completeEnd () {
      this.btnLoading = true
      completeEnd(this.applyid, this.taskid, this.currentUser.userId).then((res) => {
        if (res.code == 0) {
          this.$message.success('提交成功')
          // 跳转到上一级页面
          this.$router.push({
            path: '/SuperviseTodo/'
          })
        } else {
          this.$message.error('提交失败')
        }
      }).finally(() => {
        this.btnLoading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .file-css {
    /* display: block; */
    display: flex;
    margin-bottom: 5px;
    word-break: break-all;
    flex-direction: row;
    justify-content: space-between;
    text-align: left;
  }
  .line {
    text-overflow: -o-ellipsis-lastline;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    line-clamp: 3;
    -webkit-box-orient: vertical;
  }

  .beyond_hiding {
    width: 80%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    display: inline-block;
  }

  .download_div {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    display: inline-block;
    display: flex;
    align-items: flex-end;
    justify-content: center;
  }
  ::v-deep .ant-collapse-header {
    font-size: 16px;
    font-weight: bold;
  }
  .button_flex {
    display: flex;
    align-items: center;
  }
  .feedBack_div {
    ::v-deep .ant-table-thead > tr > th {
      background: #f2f8fc;
      // color: red;
    }
    ::v-deep .ant-table-column-title {
      font-weight: bold;
    }
  }
  .operate_btn_div {
    display: flex;
    align-items: center;
    flex-direction: row-reverse;
    justify-items: center;
    margin: 16px 0px;
  }
</style>
